package com.example.kotlinlearn.jetpack

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.edit
import androidx.lifecycle.ViewModelProvider
import com.example.kotlinlearn.R
import com.example.kotlinlearn.databinding.ActivityJetpackBinding

class JetpackActivity : AppCompatActivity() {

    lateinit var binding:ActivityJetpackBinding

    lateinit var viewModel: MainViewModel

    lateinit var sp:SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityJetpackBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //创建存储实例
        sp = getPreferences(Context.MODE_PRIVATE)
        val countSave = sp.getInt("count_save",0)
        //创建viewmodel
        viewModel = ViewModelProvider(this,MainViewModelFactory(countSave)).get(MainViewModel::class.java)
        binding.button.setOnClickListener {
            viewModel.count++
            refreshCount()
            lifecycle.currentState.toString()
            Toast.makeText(this,"当前活动状态:${lifecycle.currentState.toString()}",Toast.LENGTH_SHORT).show()
        }
        //清零
        binding.button1.setOnClickListener {
            viewModel.count=0
            refreshCount()
        }
        refreshCount()
        //增加活动感知器
        lifecycle.addObserver(MyObserver(lifecycle))

    }

    override fun onPause() {
        super.onPause()
        //活动不可见时保存数据
        sp.edit { putInt("count_save",viewModel.count) }
    }

    fun refreshCount(){
        binding.text.text = viewModel.count.toString()
    }
}